package com.alipay.util;



import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.junit.Test;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;


/**
 * FTP工具类
 *
 * 支付宝沙盒：https://docs.open.alipay.com/200/105311/
 */
public class AlipayRefund {
		//支付宝连接器
	   private AlipayClient alipayClient;
	   //支付宝退款请求
	   private AlipayTradeRefundRequest alipayRefundRequest;
	   //支付宝退款查询请求
	   private AlipayTradeFastpayRefundQueryRequest alipayRefundQueryRequest;
	   //log4j优化包
	   private Logger logger = Logger.getLogger(AlipayRefund.class);

		//阿里退款地址，支付宝网关
	   private String alipayUrl="https://openapi.alipaydev.com/gateway.do";//"https://openapi.alipay.com/gateway.do"正式环境
	   //退款APP的APPID
	   private String appId="2016092600598676";
	   //加密后私钥
	   private String privateKey="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCZDCopqU7EGXGWMXA8KLmlT+K1HUlfqQUko7DWbwR8py+pUCHZoXr4EUA3B1UJ5RPom1Xr39SAVZgat2Vx0iP/KP9CrPcu10z5tDijwWbJFl0XFWYavoCokeDF6auUS0ewY6y1/kcYz0nB1tnx7ZOEmUGjxQOlVu/00FNeYRI6hcKXU0EhE6JFyZq8h0xInHRjrTdJszSM+S55z6PDe5beuByzoeU23OHlmebkIQvBPIcdeZ+9dSlc33T3w0UntrtXPm+wGHxRsWE4QOMGZ7D2HR0sTVZogVEQ6a8LsW/4ayURqGDjveaSxqPBX4YIkSYw3dqTFg4MH1TK03QeSobJAgMBAAECggEBAIsOjHiSBqkSXSwT+2ANuK/FJ71bwMET90JVIGWVNUR1O07hKgBtQieGtQvKs69r3mzoRmcsVg3Mt4j+vUNvpZk/DL7uHSEIKj5vS08ueE+Y7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WL9+SWYonLZRPU+R+Ly4F3m8ULH+JaM3EdFt2MM0A";
	   //请求头类型 json
	   private String requestType="json";
	   //请求编码格式 GBK
	   private String requestCharacterCode="GBK";
	   //RSA2(SHA256)密钥 加密密钥
	   private String alipayPublicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4mMCWIjfOBE7UnAZ25U4bGYxydkxcU3BQ4YBP0DBXkvvFSb+9gG0rwfIeEWEdWugmFs7j++w1bev+UQ290AkYXwNyVeJqED/QyPfu6kKThiowP2TTVqVksjE+EZVpEX37f+eeB6MN0Nx2MS2UvliAu/4d55C+tZpkcT1VzezZFOf0yTHU0lkDkHqZZ4pwXrQRTH1kttt2PMe2zYAlgSNs37OANCumOfugnahXl4Ne86AhSNP7Zz5H4/2jRN6kQP8PDSkm9wwLE3O5YEtO3sF1ULr8JtsfZenNMsePZA6d4/j1kUWTf4qGGBrQnL9sfYxwt+6JTcAwaEg9Uz4YYFXxwIDAQAB";
	   //加密类型 加密类型
	   private String EncryptionType="RSA2";

	   //支付及退款条形码号码
	   private String out_trade_no = "2131231412346";
	   //订单号
	   private String trade_no = "2019032022001437341000003651";
	   //退款金额
	   private double refund_amount = 0.99;
	   //退款唯一标识（t_refund_query 的 32位UUid）
	   private String out_request_no = "HZ01RF001";


    public static void main(String[] args) {
    	AlipayRefund alipayRefund = new AlipayRefund();
//    	String strResponse =alipayRefund.alipayRefundRequest();
    	String strResponse =alipayRefund.alipayRefundQueryRequest();
    	System.out.println(strResponse);
    }

	/**
	 * @ alipayRefundRequest ＜支付宝退款请求＞
	 * @param out_trade_no 订单支付时传入的商户订单号,不能和 trade_no同时为空。
	 * @param trade_no 支付宝交易号，和商户订单号不能同时为空
	 * @param refund_amount 需要退款的金额，该金额不能大于订单金额,单位为元，支持两位小数
	 * @param out_request_no 退款唯一标识（t_refund_query 的 32位UUid）
	 * @return
	 * jsonStr:[{"body":"{\"alipay_trade_refund_response\":{\"code\":\"10000\",\"msg\":\"Success\",\"buyer_logon_id\":\"gvl***@sandbox.com\",\"buyer_user_id\":\"2088102177637345\",\"fund_change\":\"N\",\"gmt_refund_pay\":\"2019-03-15 10:48:50\",\"out_trade_no\":\"21312314123\",\"refund_detail_item_list\":[{\"amount\":\"99999.99\",\"fund_channel\":\"ALIPAYACCOUNT\"}],\"refund_fee\":\"99999.99\",\"send_back_fee\":\"99999.99\",\"trade_no\":\"2019031422001437340500543504\"},\"sign\":\"uivKYdvNRoXUU1aur8XH1dPJSPmUyecjX/Zyn8HHc4dL6OSyNi4rVWexgq4reS++MLjhS4Mdz9zd/OL0uk3PESug7k2GRzXpeCIWCub0R8+l+a++MKYR+YsVIfEdgRF595/79La6yEW/xPp/hL1KQZDGSUWxcL27t1x4L/o3ZvfqF1+3tCFfJFiXVkdij6t0bHyY9ORwGNE61CrstvK3ZovCswXV+gW1u8tXY3ceujovODbQIsLveorVPL2Afo/+9bq5EpzY/8QN+00iqItlwloVEQ/tiGXhNrzwjKWvc9niLhDepoakX0RFUHl/emc5vNe4HammkZ9AejOr52kwBQ==\"}","buyerLogonId":"gvl***@sandbox.com","buyerUserId":"2088102177637345","code":"10000","errorCode":"10000","fundChange":"N","gmtRefundPay":{"date":15,"day":5,"hours":10,"minutes":48,"month":2,"seconds":50,"time":1552618130000,"timezoneOffset":-480,"year":119},"msg":"Success","openId":"","outTradeNo":"21312314123","params":{"biz_content":"{\"out_trade_no\":\"21312314123\",\"trade_no\":\"2019031422001437340500543504\",\"refund_amount\":99999.99}"},"refundDetailItemList":[{"amount":"99999.99","fundChannel":"ALIPAYACCOUNT","fundType":"","realAmount":""}],"refundFee":"99999.99","sendBackFee":"99999.99","storeName":"","subCode":"","subMsg":"","success":true,"tradeNo":"2019031422001437340500543504"}]
	 * jsonStr:[{"body":"{\"alipay_trade_refund_response\":{\"code\":\"10000\",\"msg\":\"Success\",\"buyer_logon_id\":\"gvl***@sandbox.com\",\"buyer_user_id\":\"2088102177637345\",\"fund_change\":\"Y\",\"gmt_refund_pay\":\"2019-03-20 17:30:31\",\"out_trade_no\":\"2131231412346\",\"refund_detail_item_list\":[{\"amount\":\"0.99\",\"fund_channel\":\"ALIPAYACCOUNT\"}],\"refund_fee\":\"0.99\",\"send_back_fee\":\"0.99\",\"trade_no\":\"2019032022001437341000003651\"},\"sign\":\"u5+nXBnyhHMBFeiPwgklEvI/h03I+3yRczis/ONI39qCMPk2FOLDQWg6EWcBYtOUKsTuBZ0o7xBcoVC8RqoaOg6W1JjlayY4vBGdX2TIZlowOGJjeP13nVooCpneh0HxKh7+hA1HIwSfuUYk23V7po9TxNQEPRNd5SjV6DtilpuFMYLb+6QpMAF67qhBBkgg6q2jXWtM5igHNn4egbop+ePfaNiyVM5jTXcgYcIA/9Dip/asp+wsYFytOzgvAKHmYhhwVBRsGj9hpbCIlVPIDpXL+xxYhxrkcS4AIU+ZnI5XJTda8uhsEiM2xeE29YmZgT7kiq11nAgTIrijySNBQA==\"}","buyerLogonId":"gvl***@sandbox.com","buyerUserId":"2088102177637345","code":"10000","errorCode":"10000","fundChange":"Y","gmtRefundPay":{"date":20,"day":3,"hours":17,"minutes":30,"month":2,"seconds":31,"time":1553074231000,"timezoneOffset":-480,"year":119},"msg":"Success","openId":"","outTradeNo":"2131231412346","params":{"biz_content":"{\"out_trade_no\":\"2131231412346\",\"trade_no\":\"2019032022001437341000003651\",\"refund_amount\":0.99,\"out_request_no\":\"HZ01RF001\"}"},"refundDetailItemList":[{"amount":"0.99","fundChannel":"ALIPAYACCOUNT","fundType":"","realAmount":""}],"refundFee":"0.99","sendBackFee":"0.99","storeName":"","subCode":"","subMsg":"","success":true,"tradeNo":"2019032022001437341000003651"}]
	 */
//    @Test
//	public void alipayRefundRequest(){
	public String alipayRefundRequest(){
		// 发送请求
		String strResponse = null;
		try {
//			alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do","2016092600598676","MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCZDCopqU7EGXGW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RDm8PUjg3/LsPc5/1AsNtr4N6TjxCv1SKT3+Kfy1GXyInE3HbhGFUk37MN1fqHewGgnDM53Ak6avv4LsSy8h/vaYb9qXJHxsW93UkYpzqq33Bw9dFGEJnL4r8qE7+/4n9WQKBgE/AyVzZTxUuyP9vRMTqgU4G/D2hXPlRmjkS4rX1WPvidhsFUb+/IIRwMpN8YxNXHw5lf1TVblRsFPvrvb3dSoztJ4pbAl6JsdlOXXqJA5i88g9ZAJj2s7EgMuYzfyBgVFgT9lmZyK8chLoBSgDdlCUQI9Drr//oGGir+kVnWmAhAoGBANJ9dkML6YfU7WmuEMNHtXKGZDtNXEhUGUl3KwJ3C5jozdYvvXHBU/xSBedLq402C8kIbFbLbAzrbxv2IzsYDVKFvsHCrvtwnmBm6XSOeoxBdVkxlzU6XRUla1NI5ViY37bWL9+SWYonLZRPU+R+Ly4F3m8ULH+JaM3EdFt2MM0A"
//					,"json","GBK","MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4mMCWIjfOBE7UnAZ25U4bGYxydkxcU3BQ4YBP0DBXkvvFSb+9gG0rwfIeEWEdWugmFs7j++w1bev+UQ290AkYXwNyVeJqED/QyPfu6kKThiowP2TTVqVksjE+EZVpEX37f+eeB6MN0Nx2MS2UvliAu/4d55C+tZpkcT1VzezZFOf0yTHU0lkDkHqZZ4pwXrQRTH1kttt2PMe2zYAlgSNs37OANCumOfugnahXl4Ne86AhSNP7Zz5H4/2jRN6kQP8PDSkm9wwLE3O5YEtO3sF1ULr8JtsfZenNMsePZA6d4/j1kUWTf4qGGBrQnL9sfYxwt+6JTcAwaEg9Uz4YYFXxwIDAQAB","RSA2");
			alipayClient = new DefaultAlipayClient(alipayUrl,appId,privateKey,requestType,requestCharacterCode,alipayPublicKey,EncryptionType);
			alipayRefundRequest = new AlipayTradeRefundRequest();
			StringBuffer sb = new StringBuffer();
			sb.append("{");
			sb.append("\"out_trade_no\":\"" + out_trade_no + "\","); //商户订单号
			sb.append("\"trade_no\":\"" + trade_no + "\",");//支付宝交易号
			sb.append("\"refund_amount\":" + refund_amount+ ",");//退款的金额   + ","
			sb.append("\"out_request_no\":\"" + out_request_no +"\""                             );//,
//			sb.append("\"refund_currency\":\"USD\","                                  );
//			sb.append("\"refund_reason\":\"正常退款\","                                 );
//			sb.append("\"operator_id\":\"OP001\","                                    );
//			sb.append("\"store_id\":\"NJ_S_001\","                                    );
//			sb.append("\"terminal_id\":\"NJ_T_001\","                                 );
//			sb.append("\"goods_detail\":[{"                                     );
//			sb.append("\"goods_id\":\"apple-01\","                            );
//			sb.append("\"alipay_goods_id\":\"20010001\","                             );
//			sb.append("\"goods_name\":\"ipad\","                                      );
//			sb.append("\"quantity\":1,"                                               );
//			sb.append("\"price\":2000,"                                               );
//			sb.append("\"goods_category\":\"34543238\","                              );
//			sb.append("\"categories_tree\":\"124868003|126232002|126252004\","        );
//			sb.append("\"body\":\"特价手机\","                                          );
//			sb.append("\"show_url\":\"http://www.alipay.com/xxx.jpg\""                );
//			sb.append("}],"                                                   );
//			sb.append("\"refund_royalty_parameters\":[{"                        );
//			sb.append("\"royalty_type\":\"transfer\","                        );
//			sb.append("\"trans_out\":\"2088101126765726\","                           );
//			sb.append("\"trans_out_type\":\"userId\","                                );
//			sb.append("\"trans_in_type\":\"userId\","                                 );
//			sb.append("\"trans_in\":\"2088101126708402\","                            );
//			sb.append("\"amount\":0.1,"                                               );
//			sb.append("\"amount_percentage\":100,"                                    );
//			sb.append("\"desc\":\"分账给2088101126708402\""                            );
//			sb.append("}],"                                                   );
//			sb.append("\"org_pid\":\"2088101117952222\""                              );
			sb.append("}");
			alipayRefundRequest.setBizContent(sb.toString());
			AlipayTradeRefundResponse response = alipayClient.execute(alipayRefundRequest);
			//创建JSONArray数组，并将json添加到数组
			JSONArray array = new JSONArray();
			array.add(response);
			//转换为字符串
			String jsonStr = array.toString();
			System.out.println("jsonStr:"+jsonStr);
			strResponse=response.getCode();
			System.out.println("strResponse:"+strResponse);
			if ("10000".equals(response.getCode())) {
				strResponse="退款成功";
			}else {
				strResponse=response.getSubMsg();
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
//			logger.getLogger();
			System.out.println(ex.toString());
		}
	 	return strResponse;
	}

    /**
     * 支付宝退款查询接口
     * @ alipayRefundQueryRequest ＜支付宝退款查询＞
	 * @param out_trade_no 订单支付时传入的商户订单号,不能和 trade_no同时为空。
	 * @param trade_no 支付宝交易号，和商户订单号不能同时为空
	 * @param refund_amount 需要退款的金额，该金额不能大于订单金额,单位为元，支持两位小数
	 * @param out_request_no 退款唯一标识（t_refund_query 的 32位UUid）
     * @return
     * jsonStr:[{"body":"{\"alipay_trade_fastpay_refund_query_response\":{\"code\":\"10000\",\"msg\":\"Success\",\"out_request_no\":\"HZ01RF001\",\"out_trade_no\":\"2131231412346\",\"refund_amount\":\"0.99\",\"total_amount\":\"0.99\",\"trade_no\":\"2019032022001437341000003651\"},\"sign\":\"hyTBqDEyHY1fYLAGmPr4Cx7dmn2WpaaUGBd5VhJ4nERv3dnVp7WPt2bKTOthz02k1P6I+t731eIuApBQyLKxpNkcbTsfdAL5B2gOYcVLFZEfQJfR5al/Zxnj9MkEq2P+ySQBMNOJuNeCvv9T3/nC57RN9JPJBNcJWla+c79Q55LnW7CHeiO3wDQ6mZaBmbp3SijHO/lPpKydUBz3JATPNoUsxTqcZrV0OVQXGpNk21D2CkoKRGtVSbG8YHbqBDijd3Si0x9gNyzJdpDn1Y01xQiHWuRJUXZwVgtZbEwCt0KtlxCALAQARAutW/GJux6xNdyU6Lqz595MsjS8XgmqyQ==\"}","code":"10000","errorCode":"10000","msg":"Success","outRequestNo":"HZ01RF001","outTradeNo":"2131231412346","params":{"biz_content":"{\"out_trade_no\":\"2131231412346\",\"trade_no\":\"2019032022001437341000003651\",\"refund_amount\":0.99,\"out_request_no\":\"HZ01RF001\"}"},"refundAmount":"0.99","refundReason":"","subCode":"","subMsg":"","success":true,"totalAmount":"0.99","tradeNo":"2019032022001437341000003651"}]
     */
//	@Test
	public String alipayRefundQueryRequest(){
		String strResponse = null;
		try {
			alipayClient = new DefaultAlipayClient(alipayUrl,appId,privateKey,requestType,requestCharacterCode,alipayPublicKey,EncryptionType);
			alipayRefundQueryRequest = new AlipayTradeFastpayRefundQueryRequest();
			 StringBuffer sb = new StringBuffer();
				sb.append("{");
				sb.append("\"out_trade_no\":\"" + out_trade_no + "\","); //商户订单号
				sb.append("\"trade_no\":\"" + trade_no + "\",");//支付宝交易号
				sb.append("\"refund_amount\":" + refund_amount+ ",");//退款的金额   + ","
				sb.append("\"out_request_no\":\"" + out_request_no +"\""                             );//,
				sb.append("}");
			alipayRefundQueryRequest.setBizContent(sb.toString());
			AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(alipayRefundQueryRequest);
			JSONArray array = new JSONArray();
			array.add(response);
			//转换为字符串
			String jsonStr = array.toString();
			System.out.println("jsonStr:"+jsonStr);
			strResponse = response.getCode();
			System.out.println("strResponse:"+strResponse);
			if(response.isSuccess()){
			System.out.println("调用成功");
			} else {
			System.out.println("调用失败");
			}
	} catch (Exception ex) {
		logger.error(ex.getMessage(), ex);
//		logger.getLogger();
		System.out.println(ex.toString());
	}
		return strResponse;
	}
}